import 'dart:async';
import 'dart:convert';
import 'package:fluttermqttdemo/listeventbus.dart';
import 'package:fluttermqttdemo/mqtttool.dart';
import 'package:flutter/material.dart';
import 'package:mqtt_client/mqtt_client.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),

      home: MyHomePage(title: 'Flutter Demo Home Page'),

    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  StreamSubscription<List<MqttReceivedMessage<MqttMessage>>> _listenSubscription;
  StreamSubscription<Map<dynamic, dynamic>> _listEvenBusSubscription;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _listEvenBusSubscription =
        ListEventBus.getDefault().register<Map<dynamic, dynamic>>((msg) {
          String topic = msg["topic"];
          var message = msg["payload"];
          print("监听的 topc= $topic, payload= $message");
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[

            Container(
              child: RaisedButton(
                onPressed: (){
                  connectTestQMTT();
                },
                //onPressed: connectTest,
                child: Text(
                  "连接服务",
                  style: TextStyle(fontSize: 20, color: Colors.purple),
                ),
              ),
            ),
//            Container(
//              child: RaisedButton(
//                onPressed: _subscribeTopic,
//                child: Text(
//                  "订阅主题",
//                  style: TextStyle(fontSize: 20, color: Colors.purple),
//                ),
//              ),
//            ),
//            Container(
//              child: RaisedButton(
//                onPressed: _unSubscribeTopic,
//                child: Text(
//                  "取消订阅主题",
//                  style: TextStyle(fontSize: 20, color: Colors.purple),
//                ),
//              ),
//            ),
            Container(
              child: RaisedButton(
                onPressed: _publishTopic,
                child: Text(
                  "发布主题",
                  style: TextStyle(fontSize: 20, color: Colors.purple),
                ),
              ),
            ),
//            Container(
//              child: RaisedButton(
//                onPressed: _startListen,
//                child: Text(
//                  "开始监听",
//                  style: TextStyle(fontSize: 20, color: Colors.purple),
//                ),
//              ),
//            ),
            Container(
              child: RaisedButton(
                onPressed: _disconnect,
                child: Text(
                  "断开服务",
                  style: TextStyle(fontSize: 20, color: Colors.purple),
                ),
              ),
            )
          ],
        ),
      ),
     // This trailing comma makes auto-formatting nicer for build methods.
    );
  }

//  建立连接
  connectTestQMTT() async {

    //mqtt消息机制
//    host = tcp://47.114.209.185:32006
//    userName = pos
//    passWord = xUZMgV23C1dru6Nq8TSl
//    qos = 0
//    connectTime = 10
//    aliveInterval = 10


    String server = "47.114.209.185";
    int port = 32006;
    String clientId = "0202080001";
    String userName = "pos";
    String password = "xUZMgV23C1dru6Nq8TSl";
    MqttTool.getInstance()
        .connect(server, port, clientId, userName, password)
        .then((v) {
      if (v.returnCode == MqttConnectReturnCode.connectionAccepted) {
        print("恭喜你~ ====mqtt连接成功");
        _startListen();
        _subscribeTopic();
      } else if (v.returnCode == MqttConnectReturnCode.badUsernameOrPassword) {
        print("有事做了~ ====mqtt连接失败 --密码错误!!!");
      } else {
        print("有事做了~ ====mqtt连接失败!!!");
      }
    });


//      Test test = new Test();
//      test.connect();

  }

//  订阅主题
  _subscribeTopic() {
    String clientId = "0202080001";
    String topic = "0_020_208_0001";
    MqttTool.getInstance().subscribeMessage(topic);
  }

//  取消订阅
  _unSubscribeTopic() {
    String clientId = "0202080001";
    String topic = "0_020_208_0001";
    MqttTool.getInstance().unsubscribeMessage(topic);
  }

//  发布消息
  _publishTopic() {
    String topic = "0_020_208_0001";
    String str1 = "测试消息";
    MqttTool.getInstance().publishMessage(topic, str1);
  }

//  监听消息的具体实现
  _onData(List<MqttReceivedMessage<MqttMessage>> data) {
    final MqttPublishMessage recMess = data[0].payload;
    final String topic = data[0].topic;
    final String pt = Utf8Decoder().convert(recMess.payload.message);
    String desString = "topic is <$topic>, payload is <-- $pt -->";
    print("string =$desString");
    Map p = Map();
    p["topic"] = topic;
    p["type"] = "string";
    p["payload"] = pt;
    ListEventBus.getDefault().post(p);
  }

//  开启监听消息
  _startListen() {
   _listenSubscription = MqttTool.getInstance().updates().listen(_onData);
  }

//  断开连接
  _disconnect() {
    MqttTool.getInstance().disconnect();
  }




  //连接测试
  void connectTest() {

//    TestMqtt testMqtt = new TestMqtt();
//    testMqtt.connect();

  }
}